/**
 * 
 * 
 * @param {object} options 配置参数
 * 
 * @param {string} options.viewStyle.backgroundColor   默认值 rgba(255,255,255,0) 透明
 * @param {number} options.viewStyle.top   无默认值  当传入top时 优先执行传入top的值, 不传top时,  initPosition 默认值为左下
 * @param {number}options.viewStyle.left 	无默认值
 * @param {number} options.viewStyle.width 默认值 100   输入时以rpx的数值输入,不带单位
 * @param {number} options.viewStyle.height 默认值 100  输入时以rpx的数值输入,不带单位
 * @param {string} options.mainImage 默认值 '/static/logo.png'  必传
 * @param {string} options.initPosition 默认值 'leftBottom'   左上 leftTop 左中 leftCenter 左下 leftBottom  右上 rightTop  右中 rightCenter 右下 rightBottom
 * @param {number} options.moveSpeed  默认值 0  悬浮球回弹速度
 * @param {Boolean} options.isMove 默认值 true  是否自动靠边
 * 
 * @param {function} func 点击事件执行函数,传入函数时不能带括号!!!!  @returns {object} 
 * @param {Boolean} show  默认值为true, 为true时默认显示,为false时需要手动操作
 */

const {
	statusBarHeight
} = uni.getSystemInfoSync();
let systemInfo = uni.getSystemInfoSync();

class LevitatedSphere {
	constructor(options = {}, func, show = false) {
		this.options = options;
		this.func = func;
		this.isShow = show;
		this.view = null;
		this.bitmap = null;
		this.width = null;
		this.axle = null;
		this.height = null;
		this.clickLoading = false;

		this.systemInfo = uni.getSystemInfoSync();
		this.parameterProcessing(options);
		this.init();
		// 新增：屏幕旋转监听
		this.orientationListener = () => this.handleScreenRotate();
		uni.onWindowResize(this.orientationListener);
	}

	handleScreenRotate() {
		let that = this;
		setTimeout(() => {
			that.systemInfo = uni.getSystemInfoSync(); // 更新屏幕信息
			systemInfo = uni.getSystemInfoSync();
			// 重新计算位置
			function removePx(str) {
				if (str.includes('px')) {
					return str.replace('px', '');
				}
				return str;
			}
			let backHeight = removePx(String(that.options.viewStyle.height));
			that.options.viewStyle.height = Number(backHeight);
			const position = that.initPositionHandler(that.options.initPosition, that.options);

			// 更新视图样式
			that.view.setStyle({
				...that.options.viewStyle,
				top: position.top + 'px',
				left: position.left + 'px',
			});

		}, 500);
	}

	parameterProcessing(options) {
		const position = this.initPositionHandler(options.initPosition, options);
		this.options.viewStyle = {
			opcity: options.viewStyle?.opcity || 1,
			backgroundColor: options.viewStyle?.backgroundColor || 'rgba(0,0,0,0)',
			top: `${options.top ?? position.top}px`,
			left: `${options.left ?? position.left}px`,
			width: `${uni.upx2px(options.viewStyle?.width ?? 100)}px`,
			height: `${uni.upx2px(options.viewStyle?.height ?? 100)}px`,
		};
		this.options.show = options.show;
		this.options.moveSpeed = options.moveSpeed ?? 0;
		this.options.isMove = options.isMove == false ? false : true;
		this.width = this.options.viewStyle.width.replace("px", "");
		this.height = this.options.viewStyle.height.replace("px", "");
		// console.log('this.options', this.options);
	}

	init() {
		this.loadPicture().then(() => {
			let webview = null;
			webview = new plus.nativeObj.View(`levitated-sphere`, this.options.viewStyle);
			webview.drawBitmap(
				this.bitmap, {}, {
					width: this.options.viewStyle.width,
					height: this.options.viewStyle.height,
					left: 0,
					top: 0
				},
				"runbackground"
			);
			webview.interceptTouchEvent(true);
			webview.addEventListener("click", (res) => {
				if (this.clickLoading) return;
				this.clickLoading = true;
				this.func && this.func({
					type: 'click',
					msg: '点击事件',
					data: {},
					options: this.options
				});
			}, false);
			webview.addEventListener("touchstart", (res) => {
				this.clickLoading = false;
				this.axle = {
					xAxle: res.pageX,
					yAxle: res.pageY,
					clientX: res.clientX,
					clientY: res.clientY
				};
			}, false);
			webview.addEventListener("touchmove", res => {
				this.clickLoading = false;
				const {
					screenX,
					screenY,
					pageX,
					pageY
				} = res;
				if (Math.abs(this.axle.xAxle - pageX) > 10 || Math.abs(this.axle.yAxle - pageY) >
					10) {
					let x = pageX - this.axle.clientX;
					let y = pageY - this.axle.clientY;
					if (x >= systemInfo.screenWidth - this.width) {
						x = systemInfo.screenWidth - this.width;
					}
					if (y >= systemInfo.screenHeight - this.height) {
						y = systemInfo.screenHeight - this.height;
					}
					webview.setStyle({
						...this.options.viewStyle,
						top: y,
						left: x,
					});
					this.func && this.func({
						type: 'move',
						msg: '移动事件',
						data: {
							xAxle: x,
							yAxle: y,
							options: this.options,
							systemInfo
						}
					});
					this.clickLoading = true;
				}
			}, false);
			webview.addEventListener('touchend', res => {
				if (!this.options.isMove) return;
				if (!this.clickLoading) return;
				this.keepToTheSideAnimation(res.pageX, systemInfo.screenWidth);
			}, false);
			this.view = webview;
			if (this.isShow) {
				this.view.show();
			}
		});
	}
	keepToTheSideAnimation(x, width) {
		const _that = this;
		let index = x;
		let timer;
		if (x > width / 2) {
			timer = setInterval(() => {
				index++;
				_that.view.setStyle({
					left: index
				});
				if (index >= width - this.width) {
					_that.view.setStyle({
						left: width - this.width
					});
					clearInterval(timer);
				}
			}, _that.moveSpeed);
		} else {
			timer = setInterval(() => {
				index--
				_that.view.setStyle({
					left: index
				});
				if (index <= 0) {
					clearInterval(timer);
				}
			}, _that.moveSpeed);
		}
	}
	loadPicture() {
		this.bitmap = new plus.nativeObj.Bitmap("lp-bg");
		return new Promise((resolve, reject) => {
			this.bitmap.load(
				`_www${this.options.mainImage}`,
				// `_www${this.options.url}`,
				() => {
					resolve();
				},
				error => {
					reject(error);
				}
			);
		});
	}
	initPositionHandler(position, option) {
		let left;
		let top;
		const right = systemInfo.screenWidth - uni.upx2px(option.viewStyle?.width ?? 500);
		const center = (systemInfo.screenHeight / 2) - uni.upx2px(option.viewStyle?.height ?? 500) / 2;
		const bottom = systemInfo.screenHeight - uni.upx2px(option.viewStyle?.height ?? 500) - 100
		switch (position) {
			case 'leftTop':
				left = 0;
				top = 50;
				break;
			case 'leftCenter':
				left = 0;
				top = center;
				break;
			case 'leftBottom':
				left = 0;
				top = bottom;
				break;
			case 'rightTop':
				left = right;
				top = 50;
				break;
			case 'rightCenter':
				left = right;
				top = center;
				break;
			case 'rightBottom':
				left = right;
				top = bottom;
				break;
			default:
				// 默认值左下
				left = 0;
				top = bottom;
				break;
		}

		return {
			top,
			left
		}
	}

	show() {
		this.view.show();
	}
	hide() {
		this.view.hide();
		// this.view.close();
	}
	destroy() {
		uni.offWindowResize(this.orientationListener);
		this.view.close();
	}
	// 动态更新图片方法
	updateImage(newImagePath) {
		this.options.mainImage = newImagePath;
		this.loadPicture().then(() => {
			this.view.drawBitmap(
				this.bitmap, {}, {
					width: this.options.viewStyle.width,
					height: this.options.viewStyle.height,
					left: 0,
					top: 0,
				},
				'runbackground'
			);
		});
	}
}

function initLevitatedSphere(options, func, show) {
	return new LevitatedSphere(options, func, show);
}
export default initLevitatedSphere;